package com.googlecode.perfectable.persistable.serialization;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import javax.annotation.Nullable;

import com.googlecode.perfectable.persistable.session.Identifier;
import com.googlecode.perfectable.persistable.session.InvalidReference;
import com.googlecode.perfectable.persistable.storage.Materializer;

public class PersistanceInputStream extends ObjectInputStream {
	private final Materializer materializer;

	public PersistanceInputStream(InputStream source, Materializer materializer) throws IOException {
		super(source);
		this.materializer = materializer;
		this.enableResolveObject(true);
	}

	@Override
	@Nullable
	protected Object resolveObject(@Nullable Object obj) throws IOException {
		if(obj instanceof Identifier<?>) {
			try {
				return this.materializer.materialize((Identifier<?>) obj);
			}
			catch(InvalidReference e) {
				throw new RuntimeException(e); // TODO Auto-generated catch block
			}
		}
		return super.resolveObject(obj);
	}
}
